<?php

namespace app\common\model;

use helper\JwtHandler;

class MemberModel extends BaseModel
{

  protected $table = 'member';

  /**
   * 添加会员
   * @param $data
   * @return string
   * @throws \Exception
   */
  public function add($data)
  {
    if(!isset($data['id']) && !empty($data['unionid'])){
      $member = $this->where('unionid',$data['unionid'])->find();
      if($member) $data['id'] = $member['id']; //修改用户资料
    }
    //新增时更新user_id
    if(!isset($data['id'])){
      $info = self::create($data);
      return $info['id'];
    }else{
      self::update($data);
      return $data['id'];
    }
  }

  /**
   * 用户登录
   * @param $userId
   * @return string
   * @throws \Exception
   */
  public function setToken($userId){
    $member = $this->where('id',$userId)->find();
    if(empty($member)) abort(500,'用户不存在');
    $userSig = D('live.Tic')->genSig($userId);
    $result = [
        "identity"=>'audience',
        "userId"=>$member['id'],
        "userSig"=>$userSig,
        "nick"=>$member['nick'],
        "avatar"=>$member['avatar'],
    ];
    return JwtHandler::encode($result,config('cloud.tencent.secretKey'));
  }

}
